<?php


namespace app\admin\controller;


use app\admin\common\library\FlowEngine;
use app\admin\common\Week;
use app\admin\common\WorkTime;
use app\admin\model\Department;
use app\admin\model\FlowTask;
use app\admin\model\Scheme;
use app\BaseController;
use app\Request;
use think\facade\View;

class Overtime extends BaseController
{
    protected $childrenAdminIds = [];
    protected $user_id = null;
    protected $user_name = null;
    protected $group_id = null;
    protected $group_name = null;

    public function initialize()
    {
        parent::initialize();
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->user_id          = $this->auth->id;
        $this->user_name        = $this->auth->nickname;
        $this->group_id         = $this->auth->department_id;
        $this->group_name       =
            Department::find($this->auth->department_id)->value('name');
        View::assign([
            'user_name'  => $this->user_name,
            'group_name' => $this->group_name,
        ]);
    }

    //资源显示测试11111
    public function index(Request $request)
    {

        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $user_name = $request->param('user_name');
            if ($request->has('user_name') &&
                !empty($request->get('user_name'))
            ) {
                $where[] = ["user_name", "like", $request->get('user_name').'%'];
            }
            $where[] = ["user_id", "in",$this->childrenAdminIds];
            $page   = $request->param('page');
            $result = \app\admin\model\Overtime::where($where)->order(['id'=>'desc'])
                ->paginate($limit, false, ['page' => $page])->each(function (
                $item,
                $key
            ) {
                $item['progress_status'] = checkStatus($item['status']);
                $item['task_status']     =
                    checkTaskStatus('overtime ', $item['id']);
            })->toArray();

            return json(['code'  => 200,
                         'msg'   => '',
                         'total' => $result['total'],
                         'data'  => $result['data']]);
        }
        return View::fetch();
    }

    //资源新增
    public function add(Request $request)
    {
        $flow =
            \app\admin\model\Scheme::where('flowname', 'in', ['加班'])->select();
        if ($request->isAjax()) {
            $start_time =
                $request->param('start_time') . ' ' . $request->param('s_time');
            $end_time   =
                $request->param('end_time') . ' ' . $request->param('e_time');
            if (strtotime($start_time) > strtotime($end_time)) {
                return json(['code' => 400,
                             'url'  => '',
                             'msg'  => '开始时间不能大于结束时间！']);
            }
//            $week               = new WorkTime($start_time, $end_time);
//            $week_arr           = $week->work_hours();
//            halt($week_arr);
            $timediff = strtotime($end_time)-strtotime($start_time);
            $days = intval($timediff / 86400); //天数
            //午休开始时间
            $timeBegin = strtotime($request->param('start_time').' '.'12:00'.":00"); //午休开始时间
            //午休结束时间
            $timeEnd = strtotime($request->param('end_time').' '.'14:00'.":00");//午休结束时间
            //选中的结束时间
            $curr_time = strtotime($end_time.":00");
            //选中的开始时间
            $curr_start_time = strtotime($start_time.":00");
            //如果开始时间小于14:00  结束时间大于14点
            if ($curr_start_time < $timeBegin && $curr_time > $timeEnd) { //1
                //开始时间小于12点，结束时间大于14点  减2个小时
                $hour = ((strtotime($end_time) - strtotime($start_time)) % 86400 / 3600) - (($timeEnd - $timeBegin) % 86400 / 3600); //计算小时
//                halt($hour . '开始时间小于12点，结束时间大于14点  减2个小时');
            } else if ($curr_start_time < $timeBegin && $curr_time <= $timeBegin) {
                //开始时间小于12点，结束时间小于等于12点
                $hour = ((strtotime($end_time) - strtotime($start_time)) % 86400 / 3600); //计算小时
//                halt($hour . '开始时间小于12点，结束时间小于等于12点');
            } else if ($curr_start_time >= $timeBegin && $curr_time <= $timeEnd) {
                //开始时间大于等于12点，结束时间小于等于14点
                $hour = ((strtotime($end_time) - strtotime($start_time)) % 86400 / 3600); //计算小时
//                halt($hour . '开始时间大于等于12点，结束时间小于等于14点');
            } else if ($curr_start_time >= $timeBegin && $curr_time > $curr_start_time) {
                //开始时间大于等于12点切结束时间大于开始时间
                $hour = ((strtotime($end_time) - strtotime($start_time)) % 86400 / 3600); //计算小时
//                halt($hour . '开始时间大于等于12点切结束时间大于开始时间');
            } else {
                $hour = ((strtotime($end_time) - strtotime($start_time)) % 86400 / 3600); //计算小时
            }
            //else if ($curr_time >= $timeBegin){
            //                $hour=((strtotime($end_time)-strtotime($start_time))%86400/3600) - (($curr_time - $timeBegin)%86400/3600); //计算小时
            //                halt($hour.'----------');
            //            }else{
            //                $hour=((strtotime($end_time)-strtotime($start_time))%86400/3600); //计算小时
            //            }
            if ($days > 0){
                $days = 24 * $days;
            }
            $hours = $hour + $days;
            $data               = $request->param();
            $data['user_id']    = $this->user_id;
            $data['user_name']  = $this->user_name;
            $data['group_id']   = $this->group_id;
            $data['group_name'] = $this->group_name;
            $data['duration']   = $hours;
            $data['start_time'] = $start_time;
            $data['end_time']   = $end_time;
//            //自定义
//            $zdy =  [
//                'user_id'=>$this->user_id,
//                'user_name'=>$this->user_name,
//                'group_id'=>$this->group_id,
//                'group_name'=>$this->group_name
//            ];
//            $new_data = array_merge($data,$zdy);
//            halt($new_data);
            $res = \app\admin\model\Overtime::create($data);
            if ($res) {
                //start流程
                $scheme     = Scheme::find($data['flow_id']);
                $serial_no  = $this->getnumber($scheme['flowcode']);
                $this->flow = new FlowEngine($scheme['flowcode']);
                $config     = [
                    'instancecode' => $serial_no,
                    'start_time'   => date("Y-m-d H:i:s", time()),
                    'content'      => $data['content'],
                    'from_id'      => $res->id,
                    'from_table'   => 'overtime',
                ];
                $this->flow->start($config);
                //end流程
                return json(['code' => 200, 'url' => '', 'msg' => '成功']);
            }
        }
        View::assign('flow', $flow);
        return View::fetch();
    }


    //资源删除
    public function del(Request $request)
    {
        $ids = $request->param('ids');
        if ($ids) {
            $ids = explode(',', $ids);
            foreach ($ids as $key => $id) {
                $tasklist = FlowTask::where(['from_id'    => $id,
                                             'from_table' => 'overtime'])
                    ->select();
                if (!empty($tasklist)) {
                    //删除对应的流程任务
                    FlowTask::where(['from_id'    => $id,
                                     'from_table' => 'overtime'])->delete();
                }
            }
            $count = \app\admin\model\Overtime::destroy(array_values($ids));
            if ($count) {
                return json(['code' => 200, 'url' => '', 'msg' => '删除成功！']);
            }
        }
    }

    //资源编辑
    public function edit(Request $request)
    {
        $id    = $request->param('id');
        $model = \app\admin\model\Overtime::find($id);

        $model['st_time'] = date('Y-m-d', strtotime($model['start_time']));
        $model['s_time']  = date('H:i', strtotime($model['start_time']));
        $model['en_time'] = date('Y-m-d', strtotime($model['end_time']));
        $model['e_time']  = date('H:i', strtotime($model['end_time']));
        if ($request->isAjax()) {
            $data       = $request->param();
            $start_time =
                $request->param('st_time') . ' ' . $request->param('s_time');
            $end_time   =
                $request->param('en_time') . ' ' . $request->param('e_time');
            if (strtotime($start_time) > strtotime($end_time)) {
                return json(['code' => 400,
                             'url'  => '',
                             'msg'  => '开始时间不能大于结束时间！']);
            }
            $data['id']         = $id;
            $week               = new WorkTime($start_time, $end_time);
            $week_arr           = $week->work_hours();
            $data               = $request->param();
            $data['user_id']    = $this->user_id;
            $data['user_name']  = $this->user_name;
            $data['group_id']   = $this->group_id;
            $data['group_name'] = $this->group_name;
            $data['duration']   = $week_arr['hours'];
            $data['start_time'] = $start_time;
            $data['end_time']   = $end_time;
            $res                = \app\admin\model\Overtime::update($data);
            if ($res) {
                return json(['code' => 200, 'url' => '', 'msg' => '成功']);
            }
        }
        View::assign('model', $model);
        return View::fetch();
    }


    public function detail($id)
    {
        $model = \app\admin\model\Overtime::find($id);
        View::assign('model', $model);
        return View::fetch();
    }

    //获取数据
    public function tree(Request $request)
    {

        $overtime =
            \app\admin\model\Overtime::where(['user_id'  => $this->auth->id,
                                              'status'   => 2,
                                              'is_leave' => 0])->select()
                ->toArray();
        $data     = []; //转换到对应的格式
        foreach ($overtime as $k1 => $v1) {
            $data[]['name']     =
                $v1['start_time'] . '~' . $v1['end_time'] . '[' .
                $v1['duration'] . ']';
            $data[$k1]['value'] = $v1['id'];
            $data[$k1]['hour']  = $v1['duration'];
        }
        return json($data);
    }

    public function is_use(Request $request)
    {
        $id  = $request->param('id');
        $res = \app\admin\model\Overtime::find($id);

        if (!$res) {
            return json(['code' => 400, 'url' => '', 'msg' => '找不到该数据！']);
        }

        if ($res->is_leave === 2) {
            return json(['code' => 400,
                         'url'  => '',
                         'msg'  => '该数据已经使用,请不要重复操作！']);
        }
        $data   = [
            'id'       => $id,
            'is_leave' => 2,
        ];
        $result = \app\admin\model\Overtime::update($data);
        if ($result) {
            return json(['code' => 200, 'url' => '', 'msg' => '成功！']);
        }
    }

    public function treeList(Request $request){
        $ids = $request->param('ids');
        $user_id = $request->param('user_id');
        $status = $request->param('status',0);
        if (!empty($ids)){
            if ($ids === 'xq'){
                $jbd = \app\admin\model\Overtime::where(['user_id'=>$user_id,'status'=>2])->select()->toArray();

            }else if ($status === '-1'){
                $jbd = \app\admin\model\Overtime::where(['user_id'=>$this->auth->id,'status'=>2])->select()->toArray();
            }else{
                $jbd =  \app\admin\model\Overtime::where('id','in',$ids)->select()->toArray();
            }
        }else{
            $jbd =  \app\admin\model\Overtime::where(['user_id'=>$this->auth->id,'is_leave'=>0,'status'=>2])->select()->toArray();
        }
        foreach ($jbd as $key=>$value){
            $jbd[$key]['name'] = $value['user_name'].'-[加班内容:'.$value['content'].']-[加班时间范围:'.$value['start_time'].'-'.$value['end_time'].']-[加班时长:'.$value['duration'].']';
            $jbd[$key]['value'] = $value['id'];
            if (!empty($ids)){
                $jbd[$key]['selected'] =true;
            }
        }
        return json($jbd);
    }
}
